<template>
  <el-dialog
    top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-container>
      <el-main
        v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main"
      >
        <div class="title" style="border-bottom: 0px solid #dedede">
          <span>执行设备：</span>
          <el-button
            type="text"
            style="padding: 10px 0px 5px 0px"
            v-if="!executionDevice.deviceName || executionDevice.deviceName == ''"
            @click="toSelectExecutionDevice('执行设备', -1)"
          >
            选择执行设备</el-button
          >
          <span v-else>{{ executionDevice.deviceName }}</span>
        </div>
        <template v-if="executionDevice.deviceName && executionDevice.deviceName != ''">
          <div
            style="padding: 0px 10px 10px 0px; overflow: auto"
            :style="{ 'max-height': tabelHight }"
            class="container-main"
          >
            <el-table
              ref="elTable"
              v-loading="loading"
              size="small "
              :data="dataList"
              :row-key="(row) => row.id"
              style="width: 100%"
            >
              <af-table-column align="center" label="联动设备" width="220">
                <template slot-scope="{ row, $index }">
                  <span
                    v-if="
                      row.equipmentInfo.deviceName && row.equipmentInfo.deviceName != ''
                    "
                  >
                    {{ row.equipmentInfo.deviceName }}
                  </span>
                  <span v-else>
                    <el-button
                      type="text"
                      @click="toSelectExecutionDevice('联动设备', $index)"
                      size="mini"
                    >
                      选择设备</el-button
                    >
                  </span>
                </template>
              </af-table-column>

              <af-table-column align="center" label="规则设置" width="140">
                <template slot-scope="{ row }">
                  <el-select
                    v-model="row.actionRule"
                    placeholder="选择开关状态"
                    size="mini"
                  >
                    <el-option
                      v-for="item in actionRuleList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </af-table-column>

              <af-table-column align="center" label="设定值" width="130">
                <template slot-scope="{ row }">
                  <el-input
                    v-model="row.threshold"
                    placeholder="输入设定值"
                    clearable
                    size="mini"
                  ></el-input>
                </template>
              </af-table-column>
              <af-table-column align="center" label="时间范围" width="200">
                <template slot-scope="{ row }">
                  <el-time-picker
                    is-range
                    v-model="row.timeRange"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    size="mini"
                    format="HH:mm"
                  >
                  </el-time-picker>
                </template>
              </af-table-column>
              <af-table-column align="center" label="日期范围" width="250">
                <template slot-scope="{ row }">
                  <el-date-picker
                    type="daterange"
                    v-model="row.dateRange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="mini"
                  >
                  </el-date-picker>
                </template>
              </af-table-column>
              <af-table-column align="center" label="复盘规则" width="140">
                <template slot-scope="{ row }">
                  <el-select
                    v-model="row.repeatRule"
                    placeholder="选择复盘规则"
                    size="mini"
                  >
                    <el-option
                      v-for="item in repeatRuleList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </af-table-column>
              <af-table-column align="center" label="操作" width="80">
                <template slot-scope="{ row, $index }">
                  <el-popconfirm
                    :title="'确定删除该联动设备吗？'"
                    placement="top"
                    @confirm="deleteLinkageDevice(row, $index, '确定')"
                    @cancel="deleteLinkageDevice(row, $index, '取消')"
                  >
                    <el-button type="text" size="mini" slot="reference">
                      <span style="color: red">删除</span>
                    </el-button>
                  </el-popconfirm>
                </template>
              </af-table-column>
            </el-table>
          </div>
          <div style="margin-left: -20px">
            <el-button type="text" icon="el-icon-circle-plus" @click="addLinkageDevice"
              >添加联动设备</el-button
            >
          </div>
        </template>
      </el-main>

      <el-footer>
        <el-button
          size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false"
        >
          返回
        </el-button>
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit"
        >
          {{ params.item.id == -1 ? "提交" : "修改" }}
        </el-button>
      </el-footer>
    </el-container>

    <selecte-device
      v-if="selecteDeviceObj.isVisible"
      ref="selecteDialog"
      :dialog-visible="selecteDeviceObj.isVisible"
      :title="selecteDeviceObj.title"
      :deviceIds="deviceIds"
      @close="dialogClose('selecteDeviceObj')"
      @submit="afterSubmit"
    />
  </el-dialog>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import dataFormMixins from "@/mixins/data-form-mixins";
import SelecteDevice from "./SelecteDevice";
import deviceManageApi from "@/api/device-manage";

export default {
  name: "LinkageStrategyAdd",
  components: {
    Treeselect,
    SelecteDevice,
  },
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      tabelHight: this.getHeight(),

      executionDevice: {},
      selecteDeviceObj: {
        isVisible: false,
        title: "",
      },

      operationIndex: -1,

      dataList: [],

      actionRuleList: [
        { label: "开启", value: 1 },
        { label: "关闭", value: 2 },
      ],
      repeatRuleList: [
        {
          label: "每日一次",
          value: "1,1",
        },
        {
          label: "每日两次",
          value: "1,2",
        },
      ],

      deviceIds: [],
    };
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible;
      },
      set() {
        this.toClose();
      },
    },
  },

  created() {},
  mounted() {
    if (this.params.item.id != -1) {
      this.executionDevice = this.params.item.equipmentInfo;
      this.getDataList();
    }
  },
  methods: {
    getHeight() {
      let clientHeight = 0;
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5; // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5; // 网页可见区域高
      }
      return clientHeight - 310 + "px";
    },
    toClose() {
      this.$emit("close");
    },

    getDataList() {
      // this.dataList = [
      //   {
      //     id: 1,
      //     triggerId: 1,
      //     equipmentId: 10473,
      //     equipmentInfo: {
      //       activationTime: null,
      //       createdTime: '2023-02-09 16:52:20',
      //       createdUser: '18',
      //       deptGuid: '1d21f0eb-1a7b-4766-90dc-dda60d9c70a8',
      //       deptName: null,
      //       description: '',
      //       deviceCode: 'DX0001_8645290510533228',
      //       deviceLocation: '中关村1栋3楼',
      //       deviceModel: '',
      //       deviceType: '2',
      //       deviceName: '烟感228测试',
      //       deviceParameter: '',
      //       deviceSource: 'DX0001_8645290510533228',
      //       gridRegion: 'a9cf4c5c-75ae-44bb-9be1-cc973920cbd2',
      //       id: 10473,
      //       ipAddr: '',
      //       isActive: 0,
      //       isDelete: false,
      //       latitude: 22.86396,
      //       longitude: 108.285422,
      //       manufactor: '',
      //       manufacturingDate: null,
      //       operator: '',
      //       simNo: '',
      //       status: 3,
      //       isNormal: 1,
      //       updatedTime: '2023-02-10 03:01:10',
      //       updatedUser: null,
      //       zoonId: '',
      //       gridUnit: 'bf78ecf0-25e3-4c00-b3c6-24939c843a54',
      //       gridMount: 'b8eb717e-40eb-463a-b77a-5059beca7270',
      //       gridMountName: null,
      //       gridMountFullPath: '0003,0007,0003,0003,',
      //       gridMountFullPathText: '高新区>>中关村风情小镇>>1栋>>3楼',
      //       deviceCategory: null,
      //       realTimeParameter: null,
      //       streamUrl:
      //         'https://caps.runjian.com:10098/play.html?serial=34020000001110000001&code=34020000001320000001&aspect=fullscreen',
      //       deviceRunningState: '报警',
      //       alarmCause: null,
      //       alertTimeStr: null,
      //       deviceAddress: null,
      //       solveStatus: null,
      //       deviceStatus: null,
      //       deviceTypeName: null,
      //       lnglat: null,
      //       deptId: null,
      //       isIsolateGrid: null,
      //       serviceId: null,
      //       deviceIsLine: 1,
      //       hostId: '',
      //       hostName: null,
      //       createdTimeFrom: null,
      //       createdTimeTo: null,
      //       isIsolate: 0,
      //     }, // 设备信息
      //     actionRule: 1, // 规则设置
      //     threshold: 20, // 设定值
      //     timeRange: '00:00,23:59:59', //时间范围 例00:00,23:59:59
      //     dateRange: '2022-10-01,2022-12-10', //日期范围 例2022-10-01,2022-12-10
      //     repeatRule: '1,1', //重复规则 例 每日一次1,1
      //   },
      //   {
      //     id: 2,
      //     triggerId: 1,
      //     equipmentId: 10472,
      //     equipmentInfo: {
      //       activationTime: null,
      //       createdTime: '2023-02-09 16:50:19',
      //       createdUser: '18',
      //       deptGuid: '1d21f0eb-1a7b-4766-90dc-dda60d9c70a8',
      //       deptName: null,
      //       description: '',
      //       deviceCode: 'DX0001_8645290510533229',
      //       deviceLocation: '中关村1栋3楼',
      //       deviceModel: '',
      //       deviceType: '1',
      //       deviceName: '温感229测试',
      //       deviceParameter: '',
      //       deviceSource: 'DX0001_8645290510533229',
      //       gridRegion: 'a9cf4c5c-75ae-44bb-9be1-cc973920cbd2',
      //       id: 10472,
      //       ipAddr: '',
      //       isActive: 0,
      //       isDelete: false,
      //       latitude: 22.86396,
      //       longitude: 108.285422,
      //       manufactor: '',
      //       manufacturingDate: null,
      //       operator: '',
      //       simNo: '',
      //       status: 3,
      //       isNormal: 1,
      //       updatedTime: null,
      //       updatedUser: null,
      //       zoonId: '',
      //       gridUnit: 'bf78ecf0-25e3-4c00-b3c6-24939c843a54',
      //       gridMount: 'b8eb717e-40eb-463a-b77a-5059beca7270',
      //       gridMountName: null,
      //       gridMountFullPath: '0003,0007,0003,0003,',
      //       gridMountFullPathText: '高新区>>中关村风情小镇>>1栋>>3楼',
      //       deviceCategory: null,
      //       realTimeParameter: null,
      //       streamUrl:
      //         'https://caps.runjian.com:10098/play.html?serial=34020000001110000001&code=34020000001320000001&aspect=fullscreen',
      //       deviceRunningState: '正常',
      //       alarmCause: null,
      //       alertTimeStr: null,
      //       deviceAddress: null,
      //       solveStatus: null,
      //       deviceStatus: null,
      //       deviceTypeName: null,
      //       lnglat: null,
      //       deptId: null,
      //       isIsolateGrid: null,
      //       serviceId: null,
      //       deviceIsLine: 1,
      //       hostId: '',
      //       hostName: null,
      //       createdTimeFrom: null,
      //       createdTimeTo: null,
      //       isIsolate: 0,
      //     }, // 设备信息
      //     actionRule: 2, // 规则设置
      //     threshold: 22, // 设定值
      //     timeRange: '05:00,23:59', //时间范围 例00:00,23:59:59
      //     dateRange: '2023-01-31,2023-02-01', //日期范围 例2022-10-01,2022-12-10
      //     repeatRule: '1,2', //重复规则 例 每日一次1,1
      //   },
      // ]
      // this.dataList.forEach((ele) => {
      //   if (ele.timeRange && ele.timeRange != '') {
      //     let start = ele.timeRange.split(',')[0]
      //     let end = ele.timeRange.split(',')[1]
      //     ele.timeRange = [
      //       new Date(`2023-01-01 ${start}`),
      //       new Date(`2023-01-01 ${end}`),
      //     ]
      //   }
      //   if (ele.dateRange && ele.dateRange != '') {
      //     ele.dateRange = ele.dateRange.split(',')
      //   }
      // })
      deviceManageApi.getTriggerInfo({ triggerId: this.params.item.id }).then((res) => {
        this.dataList = res.data.data;
        this.dataList.forEach((ele) => {
          if (ele.timeRange && ele.timeRange != "") {
            let start = ele.timeRange.split(",")[0];
            let end = ele.timeRange.split(",")[1];
            ele.timeRange = [
              new Date(`2023-01-01 ${start}`),
              new Date(`2023-01-01 ${end}`),
            ];
          }
          if (ele.dateRange && ele.dateRange != "") {
            ele.dateRange = ele.dateRange.split(",");
          }
        });
      });
    },

    addLinkageDevice() {
      this.dataList.push({
        id: null,
        triggerId: null,
        equipmentId: null,
        equipmentInfo: {}, // 设备信息
        actionRule: null, // 规则设置
        threshold: null, // 设定值
        timeRange: null, //时间范围 例00:00,23:59:59
        dateRange: null, //日期范围 例2022-10-01,2022-12-10
        repeatRule: null, //重复规则 例 每日一次1,1
      });
    },
    deleteLinkageDevice(data, index, type) {
      if (type == "确定") {
        this.dataList.splice(index, 1);
        this.$message({
          message: "删除成功！",
          type: "success",
        });
      }
    },
    toSelectExecutionDevice(text, index) {
      this.operationIndex = index;
      if (index == -1) {
        this.deviceIds = [];
      } else {
        this.deviceIds = [this.executionDevice.id];
        this.dataList.forEach((ele) => {
          this.deviceIds.push(ele.equipmentInfo.id);
        });
      }

      this.selecteDeviceObj.title = "选择" + text;
      this.selecteDeviceObj.isVisible = true;
    },
    afterSubmit(data) {
      if (this.operationIndex == -1) {
        this.executionDevice = data;
      } else {
        this.dataList[this.operationIndex]["equipmentInfo"] = data;
      }
    },

    toSubmit() {
      const submitModel = {
        id: null,
        equipmentId: this.executionDevice.id,
        actionList: [],
      };
      if (this.params.item.id != -1) {
        submitModel.id = this.params.item.id;
      }

      this.dataList.forEach((ele) => {
        let timeRangeStr = null;
        let dateRangeStr = null;
        if (ele.timeRange) {
          timeRangeStr =
            this.$moment(ele.timeRange[0]).format("HH:mm") +
            "," +
            this.$moment(ele.timeRange[1]).format("HH:mm");
        }
        if (ele.dateRange) {
          dateRangeStr =
            this.$moment(ele.dateRange[0]).format("YYYY-MM-DD") +
            "," +
            this.$moment(ele.dateRange[1]).format("YYYY-MM-DD");
        }
        submitModel.actionList.push({
          equipmentId: ele.equipmentInfo.id, //设备ID
          actionRule: ele.actionRule, //规则设置：1开关状态
          threshold: ele.threshold, //设定值
          timeRange: timeRangeStr, //时间范围 例00:00,23:59:59
          dateRange: dateRangeStr, //日期范围 例2022-10-01,2022-12-10
          repeatRule: ele.repeatRule, //重复规则 例 每日一次1,1
        });
      });

      console.log("submitModel=", submitModel);
      deviceManageApi
        .dealTrigger(submitModel)
        .then((ret) => {
          this.submitLoading = false;
          this.isVisible = false;
          this.$message({
            message: "提交成功！",
            type: "success",
          });
          this.$emit("submit", "add");
        })
        .catch(() => {
          this.submitLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../../styles/part-custom";

::v-deep .el-table td:last-child {
  border-left: 0px solid #ebeef5 !important;
}

::v-deep.el-table--small .el-table__cell {
  padding: 3px 0 !important;
}
::v-deep.el-range-editor--mini .el-range-input {
  font-size: 13px;
}
::v-deep.el-button--mini {
  font-size: 13px;
}
::v-deep.el-input--suffix .el-input__inner {
  padding-right: 15px;
}
</style>
